package com.easylinkin.linkappapi.common.translate.impl;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.config.dao.SysDictItemMapper;
import com.easylinkin.linkappapi.config.dao.SysDictMapper;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.easylinkin.linkappapi.common.translate.Code2Text;
import com.easylinkin.linkappapi.common.translate.CodeTranslateor;
import com.easylinkin.linkappapi.common.translate.CodeTranslateorFactory;
import com.easylinkin.linkappapi.common.translate.TypeEnum;

@Component
@Slf4j
public class DictTranslateor implements CodeTranslateor {

    static Cache<String, Map<String, String>> dictCache;

    @Resource
    private SysDictMapper sysDictMapper;
    @Resource
    private SysDictItemMapper sysDictItemMapper;

    public DictTranslateor() {
        dictCache = CacheUtil.newLRUCache(1000);
    }

    @PostConstruct
    public void init() {
        CodeTranslateorFactory.register(this.getClass(), this);
    }

    @Override
    public String translate(Object obj, Object value, Code2Text ann) {
        if (null == value) {
            return null;
        }
        String cate = ann.value();
        if (value instanceof List) {
            List l = (List) value;
            List<String> list = new ArrayList<>(l.size());
            l.forEach((v) -> {
                String dict = translate(cate, v);
                list.add(dict);
            });
            return StrUtil.join("，", list);
        }
        if (ann.type() == TypeEnum.SPILT) {
            String strVal = value.toString();
            if (JSONUtil.isJsonArray(strVal)) {
                JSONArray array = null;
                try {
                    array = JSONUtil.parseArray(strVal);
                } catch (Exception e) {
                    log.error("obj: {}, dict: {}, error: {}", obj.getClass(), cate, e.getMessage(), e);
                }
                if (array != null) {
                    List<String> list = new ArrayList<>(array.size());
                    array.forEach((v) -> {
                        String dict = translate(cate, v);
                        list.add(dict);
                    });
                    return StrUtil.join("，", list);
                }
            } else {
                String[] split = value.toString().split(",");
                List<String> list = new ArrayList<>(split.length);
                for (String v : split) {
                    String dict = translate(cate, v);
                    list.add(dict);
                }
                return StrUtil.join("，", list);
            }
        } else {
            String dict = translate(cate, value.toString());
            if (dict != null) {
                return dict;
            }
        }
        return null;
    }

    public String translate(String cate, Object k) {
        if (null == k) {
            return null;
        }
        Map<String, String> cache = dictCache.get(cate);
        String key = k.toString();
        if (cache == null) {
            cache = new HashMap<>();
			dictCache.put(cate, cache);
        }
        String s = cache.get(key);
        if (StringUtils.isBlank(s)) {
            // 如果缓存中没有，则从数据库查询
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("dict_code_", cate);
            SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
            if (sysDict != null) {
                QueryWrapper itemQueryWrapper = new QueryWrapper();
                itemQueryWrapper.eq("dict_id_", sysDict.getId());
                itemQueryWrapper.eq("item_value_", key);
                SysDictItem sysDictItem = sysDictItemMapper.selectOne(itemQueryWrapper);
                if (sysDictItem != null) {
                    // 将查询结果放入缓存
                    cache.put(key, sysDictItem.getItemText());
                    s = sysDictItem.getItemText();
                    cache.put(key, s);
                }
            }
        }
        return s;
    }

}
